import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  operationStatusEnum,
  lampPostTypeEnum
} from '~/store/assetManagement/facilityManagement/typings'
import type { AssetLampPostDataItemType, AssetLampPostStateType, accomplishEnum } from './typings'
import type { workAreaEnum } from '~/store/assetManagement/assetAreaManage/typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import {
  ElCard,
  ElSpace,
  ElButton,
  ElLink,
  ElIcon,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { Plus, EditPen, Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { handleTrim } from '~/utils/util'
import AssetLampPostOptions from './option'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import ProSaasTable from '~/components/ProSaasTable'
import ColorfulBadge from '~/components/ColorfulBadge'
import ExportExcel from '~/components/ExportExcel'
import ImportExcel from '../../components/assetLampPostComponents/ImportExcel'
import ImportExcelUpdata from '../../components/assetLampPostComponents/ImportExcelUpdata'
import styles from '~/pages/assetManagement/index.module.scss'
import { useRouter } from 'vue-router'

export default defineComponent(function assetLampPost() {
  const store = useStore()
  const router = useRouter()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<AssetLampPostDataItemType>({})
  const state = reactive<AssetLampPostStateType>({
    importVisible: false, // 导入 弹窗是否显示
    exportVisible: false, // 导出 弹窗是否显示
    modalVisible: false, // 新增/编辑 弹窗是否显示
    importUpdataVisible: false,
    type: 'read',
    record: {}
  })

  const powerDistributionFacilitiesState = useVuexGetters('powerDistributionFacilities', [
    'operationStatusSelectList', // 投运状态
    'operationStatusEnum'
  ])
  const assetLampPostState = useVuexGetters('assetLampPost', ['lampPostTypeSelectList']) // 灯杆类型
  const assetWorkAreaState = useVuexGetters('assetWorkArea', [
    'workAreaSelectList',
    'postHeightTypeOpt'
  ])
  const userState = useVuexGetters('user', ['permission']) // 按钮权限
  // 所属街道
  const streetManagementState = useVuexGetters('streetManagement', ['streetSelectList'])

  onMounted(() => {
    //  杆高类型
    store.dispatch('assetWorkArea/GetPostHeightType')
    store.dispatch('assetLampPost/GetNodeByParentCode') // 灯杆类型 下拉列表
    store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser') // 所属区域 下拉列表
    store.dispatch('powerDistributionFacilities/GetOperationStatusSelectList') // 投运状态 下拉列表

    // 从道路管理跳转带入道路名称查询
    const row: AssetLampPostDataItemType = router.currentRoute.value.query
    if (row.id) {
      formValues.streetId?.push(row?.id as string)
      const value = streetManagementState.streetSelectList.value.filter(
        (item: workAreaEnum) => item.id === row.id
      )
      if (value.length === 0) {
        streetManagementState.streetSelectList.value.push({
          name: row.name,
          id: row.id
        })
      }
      setTimeout(() => {
        proSaasTableRef.value!?.toSearch()
      }, 500)
    }
  })

  // methods
  // 新增/编辑
  const handleChangeOptionsModal = (
    type: AssetLampPostStateType['type'],
    record?: AssetLampPostDataItemType
  ) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible && type !== 'read') proSaasTableRef.value!?.toSearch()
  }

  // 执行删除操作
  const handleDeleteSelectedData = async (params: string) => {
    await store
      .dispatch('assetLampPost/DeleteAssetLampPostInfo', {
        ids: params
      })
      .then((res) => {
        if (res?.code === 200) {
          proSaasTableRef.value!?.clearSelection?.()
          proSaasTableRef.value!?.toSearch()
          ElMessage({ type: 'success', message: '操作成功' })
        }
      })
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: AssetLampPostDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {record?.id && <p class="delete-title">确认删除数据?</p>}
          {!record?.id && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        // !record?.id
        //   ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据`
        //   : '确定将选择数据删除?',

        await store
          .dispatch('assetLampPost/CheckDeleteAssetLampPostInfo', { ids: params })
          .then(async (result) => {
            if (!result.success) return
            if (result?.data?.canDel === 0 && result?.data?.msg) {
              ElMessageBox({
                title: '确认提示',
                message: result?.data?.msg,
                showCancelButton: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                closeOnClickModal: false, // 点遮罩层不关弹窗
                draggable: true // 可拖拽
              })
                .then(() => {
                  handleDeleteSelectedData(params)
                })
                .catch(() => {
                  proSaasTableRef.value!?.clearSelection?.()
                  proSaasTableRef.value!?.toSearch()
                })
            } else {
              handleDeleteSelectedData(params)
            }
          })
      })
      .catch(() => {})
  }

  // 导入
  const handleChangeImportModal = () => {
    state.importVisible = !state.importVisible
    proSaasTableRef.value?.toSearch() // 刷新
  }

  // 批量更新
  const handleChangeImportUpdataModal = () => {
    state.importUpdataVisible = !state.importUpdataVisible
    proSaasTableRef.value?.toSearch() // 刷新
  }

  // 导出
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  //  所属街道
  const remoteMethod = (query: string) => {
    if (query) {
      store.dispatch('streetManagement/GetStreetSelectListByUser', { key: query })
    }
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空/下拉框值变 搜索
  const clearSearchTable = () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  const columns: TableColumnProps<AssetLampPostDataItemType>[] = [
    {
      label: '设备名称',
      prop: 'name',
      minWidth: 180,
      fixed: 'left',
      unFixed: true,
      sortable: true,
      disabled: true, // 不可编辑
      showOverflowTooltip: true
    },
    {
      label: '灯杆类型',
      prop: 'categoryName',
      minWidth: 180,
      sortable: true,
      disabled: true,
      showOverflowTooltip: true
    },
    {
      label: '杆高分类',
      prop: 'postHeightTypeValue',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '投运日期',
      prop: 'deliverDate',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true,
      hidden: true // 默认不展示
    },
    {
      label: '现场杆号',
      prop: 'code',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true,
      hidden: true
    },
    {
      label: '使用年限',
      prop: 'validity',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true,
      hidden: true,
      render: (_, value) => {
        return value ? <>{value} 年</> : <>{''}</>
      }
    },
    {
      label: '所属配电设施',
      prop: 'distributionName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true,
      hidden: true
    },
    {
      label: '灯具数量',
      prop: 'lampNum',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true,
      hidden: true,
      render: (_, value) => {
        return value ? <>{value} 个</> : <>{''}</>
      }
    },
    {
      label: '所属区域',
      prop: 'workAreaName',
      minWidth: 180,
      sortable: true,
      disabled: true,
      showOverflowTooltip: true
    },
    {
      label: '所属街道',
      prop: 'streetName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '投运状态',
      prop: 'isDeliver',
      minWidth: 180,
      enumValues: powerDistributionFacilitiesState.operationStatusEnum,
      sortable: true,
      disabled: true,
      showOverflowTooltip: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={(option.row.isDeliver as number) || 0}
          options={{ warning: 0, success: 1, info: 2 }}
        />
      )
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 180,
      sortable: true,
      disabled: true,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '操作',
      prop: 'options',
      fixed: 'right',
      align: 'center',
      unFixed: true,
      disabled: true,
      minWidth: 180,
      width: 210,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('assets_lamppost_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 详情
            </ElLink>
          )}
          {userState.permission.value.has('assets_lamppost_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp;编辑
            </ElLink>
          )}
          {userState.permission.value.has('assets_lamppost_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp;删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  return () => {
    // 日期变时 搜索
    const props = {
      onChange: () => {
        setTimeout(() => {
          proSaasTableRef.value!?.toSearch()
        }, 100)
      }
    }

    if (state.modalVisible) {
      return (
        <AssetLampPostOptions
          record={state.record}
          type={state.type}
          cancel={() => handleChangeOptionsModal('add')}
        />
      )
    }

    return (
      <ElCard shadow="never" class="covered-with-content">
        <ProSaasTable<AssetLampPostDataItemType>
          tableId="assetLampPost"
          ref={proSaasTableRef}
          columns={columns}
          rowKey="id"
          hasSelection
          dispatchType="assetLampPost/GetAssetLampPostList"
          headerTitle={
            <>
              {userState.permission.value.has('assets_lamppost_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}

              {userState.permission.value.has('assets_lamppost_remove') && (
                <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                  <ElIcon>
                    <Delete />
                  </ElIcon>
                  &nbsp; 删除
                </ElButton>
              )}
              {userState.permission.value.has('assets_lamppost_import') && (
                <ElButton type="primary" onClick={() => handleChangeImportModal()}>
                  <AliIcon type="icon-daoru" />
                  &nbsp; 导入
                </ElButton>
              )}
              {userState.permission.value.has('assets_lamppost_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
              {userState.permission.value.has('assets_lamppost_import') && (
                <ElButton type="primary" onClick={() => handleChangeImportUpdataModal()}>
                  <AliIcon type="icon-daoru" />
                  &nbsp; 批量更新
                </ElButton>
              )}
            </>
          }
          searchParams={{
            name:
              formValues.name === '' ? undefined : formValues.name && handleTrim(formValues.name),
            categoryId: formValues.categoryId === '' ? undefined : formValues.categoryId,
            workAreaId: formValues.workAreaId === '' ? undefined : formValues.workAreaId,
            deliverDate: undefined,
            deliverBeginTime: formValues.deliverDate?.[0],
            deliverEndTime: formValues.deliverDate?.[1]
          }}
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem key="name" prop="name">
              <ElInput
                v-model={formValues.name}
                {...{ maxlength: 30 }}
                placeholder="设备名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="categoryId" prop="categoryId">
              <ElSelect
                v-model={formValues.categoryId}
                placeholder="灯杆类型"
                clearable
                onChange={clearSearchTable}
              >
                {assetLampPostState.lampPostTypeSelectList?.value?.map((item: lampPostTypeEnum) => (
                  <ElOption key={item?.id} label={item?.dictValue} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="postHeightType" prop="postHeightType">
              <ElSelect
                v-model={formValues.postHeightType}
                placeholder="杆高分类"
                clearable
                onChange={clearSearchTable}
              >
                {assetWorkAreaState.postHeightTypeOpt?.value?.map((item: accomplishEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="isDeliver" prop="isDeliver">
              <ElSelect
                v-model={formValues.isDeliver}
                placeholder="投运状态"
                clearable
                onChange={clearSearchTable}
              >
                {powerDistributionFacilitiesState.operationStatusSelectList?.value?.map(
                  (item: operationStatusEnum) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )
                )}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="workAreaId" prop="workAreaId">
              <ElSelect
                v-model={formValues.workAreaId}
                placeholder="所属区域"
                clearable
                onChange={clearSearchTable}
              >
                {assetWorkAreaState.workAreaSelectList?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="streetId" prop="streetId" label="">
              <ElSelect
                v-model={formValues.streetId}
                clearable
                filterable
                remote
                multiple
                reserve-keyword
                remote-method={remoteMethod}
                onChange={clearSearchTable}
                placeholder="所属街道"
              >
                {streetManagementState.streetSelectList?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="deliverDate" prop="deliverDate">
              <ElDatePicker
                v-model={formValues.deliverDate}
                start-placeholder="开始投运日期"
                end-placeholder="结束投运日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                type="daterange"
                clearable
                {...props}
              />
            </ElFormItem>
          ]}
        />

        {/* 新增/编辑 */}
        {/* {state.modalVisible && (
          <AssetLampPostOptions
            visible={state.modalVisible}
            record={state.record}
            type={state.type}
            cancel={() => handleChangeOptionsModal('add')}
          />
        )} */}

        {/* 导出 */}
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="assetLampPost/ExportAssetLampPostInfo"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            exportNumber={proSaasTableRef.value?.pagination.total}
            onCancel={handleChangeExportModal}
          />
        )}

        {/* 导入 */}
        {state.importVisible && <ImportExcel doCancel={handleChangeImportModal} />}
        {/* 批量更新 */}
        {state.importUpdataVisible && (
          <ImportExcelUpdata doCancel={handleChangeImportUpdataModal} />
        )}
      </ElCard>
    )
  }
})
